#!/usr/bin/env python
# -*- coding: utf-8 -*-
#================================#
# @author: RedSoxFan and NerfSoldier
# @copyright: 2012 RedSoxFan and NerfSoldier
# @license: GNU General Public License v3.0 
#           <http://www.gnu.org/copyleft/gpl.html>
# @summary: Handles Project Tree
#=======================================#

#=======================================#
# Imports
#=======================================#
# Python
import os
from PyQt4 import QtGui, QtCore
import shutil
# DarkDev
from project import Project
#=======================================#

class ProjectTree(QtGui.QTreeWidget):
    def __init__(self,workspace,*args,**kwargs):
        super(ProjectTree,self).__init__()
        self.workspace = workspace
        self.setMouseTracking(True)
        self.setAcceptDrops(True)
        self.setDragDropMode(ProjectTree.DragDrop)

    def startDrag(self, event):
        mime = QtCore.QMimeData()
        x = QtCore.QByteArray()
        x.append(self.selectedItems()[0].toolTip(0))
        mime.setData('darkdev/treeitem', x)
        drag = QtGui.QDrag(self)
        drag.setMimeData(mime)      
        drag.exec_(QtCore.Qt.MoveAction|QtCore.Qt.CopyAction)
        
    def dragEnterEvent(self, event):
        if event.mimeData().hasFormat('darkdev/treeitem'):
            event.accept()
        elif event.mimeData().hasFormat('text/uri-list') and str(event.mimeData().data('text/uri-list')).startswith("file://"):
            event.accept()
        else:
            event.ignore()
        
    def dragMoveEvent(self, event):
        if event.mimeData().hasFormat('darkdev/treeitem'):
            event.setDropAction(event.keyboardModifiers()&QtCore.Qt.ControlModifier and QtCore.Qt.CopyAction or QtCore.Qt.MoveAction)
            event.accept()
        elif event.mimeData().hasFormat('text/uri-list') and str(event.mimeData().data('text/uri-list')).startswith("file://"):
            event.setDropAction(QtCore.Qt.CopyAction)
            event.accept()
        else:
            event.ignore()

    def dropEvent(self, event):
        item = self.itemAt(event.pos())
        if item:
            if event.mimeData().hasFormat('darkdev/treeitem'):
                # Cannot Move File Into File
                if os.path.isdir(str(item.toolTip(0))):
                    # Copy/Move DarkDev TreeItem
                    path = str(event.mimeData().data('darkdev/treeitem')).strip()
                    # Make Sure SRC and DEST Do Not Match
                    if path==str(item.toolTip(0)): return
                    proj = self.__copytree(path, item)
                    src = proj.item_for_path(path)
                    if not src: src=self.project_for_file(path)[0]
                    # If Move Clean Old Folder
                    if event.dropAction()==QtCore.Qt.MoveAction:
                        if os.path.isdir(path): shutil.rmtree(str(src.toolTip(0)))
                        else: os.remove(str(src.toolTip(0)))
                        proj.clean_folder(src)
            elif event.mimeData().hasFormat('text/uri-list'):
                # Copy URI List
                urls = str(event.mimeData().data('text/uri-list')).split("\r\n")
                for url in urls:
                    if not str(url).strip(): continue
                    path = str(url)[7:].strip().replace("/",os.sep)
                    if path.startswith("\\"): path=path[1:]
                    self.__copytree(path, item)
                
    def project_for_file(self,path):
        for child in [self.invisibleRootItem().child(i) for i in range(self.invisibleRootItem().childCount())]:
            if isinstance(child,Project):
                src = child.item_for_path(path)
                if src: return (src,child)
        return (None,None)
    
    def project_for_item(self,item):
        proj = item
        while not isinstance(proj,Project):
            proj = item.parent()
            if not proj: return None
        return proj
    
    def __copytree(self,path,item):
        if os.path.exists(path):
            proj = self.project_for_item(item)
            if os.path.isdir(path):
                shutil.copytree(path,os.path.join(str(item.toolTip(0)),os.path.basename(path)))
                item = proj.create_folder(item,os.path.basename(path))
                self.add_dir(str(item.toolTip(0)),item,proj)
            else:
                shutil.copy2(path,os.path.join(str(item.toolTip(0)),os.path.basename(path)))
                item = proj.create_file(item,os.path.basename(path))
            return proj
                    
    def add_dir(self,fol,item,proj):
        if not os.path.isdir(fol): return
        for fil in [f for f in os.listdir(fol) if f[0] not in [".","~"] and f[-1] != "~"]:
            if os.path.isdir(os.path.join(fol,fil)):
                self.add_dir(os.path.join(fol,fil),proj.create_folder(item,fil),proj)
            else:
                proj.create_file(item,fil)
        
    def mimeTypes(self):
        return QtCore.QStringList(['text/uri-list','darkdev/treeitem'])